<?php

/** base class */
require_once 'Zend/Controller/Plugin/Abstract.php';

class Application_Plugins_Initialization extends Zend_Controller_Plugin_Abstract {

	public function __construct() {
		$this->_initDatabase();
		$this->_initLogger();
		$this->_initNamespace();
		$this->_initCache();
		$this->_registerHelpersPaths();
	}

	private function _initDatabase() {
		try {
			$db = Zend_Db::factory(_DB_ADAPTER, array(
				'host'		=> _DB_HOST,
				'username'	=> _DB_USERNAME,
				'password'	=> _DB_PASSWORD,
				'dbname'	=> _DB_DATABASE,
				'profiler'	=> _DB_PROFILER,
				'port'		=> _DB_PORT
			));
			$db->query('SET NAMES utf8');
			$db->setFetchMode(Zend_Db::FETCH_OBJ);
			Zend_Db_Table::setDefaultAdapter($db);
			Zend_Registry::set('dbAdapter', $db);
			//Zend_Db_Table_Abstract::setDefaultAdapter($db);
			
			$config = array(
			    'name'           => 'session_storage',
			    'primary'        => 'id',
			    'modifiedColumn' => 'modified',
			    'dataColumn'     => 'data',
			    'lifetimeColumn' => 'lifetime'
			);
			
			//create your Zend_Session_SaveHandler_DbTable and
			//set the save handler for Zend_Session

			Zend_Session::setSaveHandler($savehandler = new Zend_Session_SaveHandler_DbTable($config));
			//cookie persist for 4 hours 
			//Zend_Session::rememberMe($seconds = (60 * 60 * 4)); 
			$seconds = 60 * 60 * 4;
			//make the session persist for 4 hours
			//we can also set lifetime on $config via lifetime key
			$savehandler->setLifetime($seconds) 
			    ->setOverrideLifetime(true); 
			Zend_Session::start();			
			
			/**
			 * connection to old site
			 */
			/*
			if (defined('_DB_IMPORT_CONNECT') && _DB_IMPORT_CONNECT) {
				$idb = Zend_Db::factory(_DB_IMPORT_ADAPTER, array(
					'host'     => _DB_IMPORT_HOST,
					'username' => _DB_IMPORT_USERNAME,
					'password' => _DB_IMPORT_PASSWORD,
					'dbname'   => _DB_IMPORT_DATABASE,
					'profiler' => _DB_PROFILER,
				));
				$idb->query('SET NAMES utf8 collate utf8_romanian_ci');
				$idb->query('SET COLLATION_CONNECTION = utf8_romanian_ci');
				Zend_Registry::set('dbImportAdapter', $idb);
			}
			*/
		} catch (Zend_Db_Adapter_Exception $e) {
			throw $e;
			//failed login, DB not running. Throw this in the logs
		} catch (Zend_Exception $e) {
			throw  $e;
			//other problem. Log it
		}
	}

	private function _initCache() {
		$frontendOptions = array(
		   'lifetime' => 7200, // cache lifetime of 2 hours
		   'automatic_serialization' => true
		);
		$backendOptions = array(
			'cache_dir' => '../Application/cache/' // Directory where to put the cache files
		);

		$cacheCore = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
		Zend_Registry::set('cacheCore', $cacheCore);

		Zend_Registry::set('HtmlPurifierCacheSerializerPath', _APP_ABSOLUTE_PATH . '/Application/cache');
		
		Zend_Db_Table_Abstract::setDefaultMetadataCache($cacheCore);
	}

	private function _initNamespace() {
		$defaultNamespace = new Zend_Session_Namespace('defaultNamespace');

		//a mix of IP and browser info. Should be fairly unique
		$sessionHash = sha1($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);

		//small trick to avoid session fixation
		if (!isset($defaultNamespace->sessionHash) || $sessionHash != $defaultNamespace->sessionHash) {
			Zend_Session::regenerateId();
			$defaultNamespace->sessionHash = $sessionHash;
		}
	}

	private function _initLogger() {
		$writer = new Zend_Log_Writer_Stream('../Application/logs/log_' . date('d-m-Y') . '.txt');
		$logger = new Zend_Log($writer);

		Zend_Registry::set('logger', $logger);
		//firephp
		$writer = new Zend_Log_Writer_Firebug();
		$logger = new Zend_Log($writer);
		Zend_Registry::set('firephp', $logger);
	}

	private function _initI18n() {

		$languages = array(1 => 'ro');
		$languages_id = array_flip($languages);
		$frontController = Zend_Controller_Front::getInstance();
		$defaultNamespace = new Zend_Session_Namespace('defaultNamespace');

		$lang = $frontController->getRequest()->getParam('setLanguage');
		//if a new language is requested, use it, otherwise use default
		if (!in_array($lang, $languages)) {
			$lang = isset($defaultNamespace->lang) && in_array($defaultNamespace->lang, $languages) ? $defaultNamespace->lang : _DEFAULT_LANGUAGE;
		 } else {
			 $defaultNamespace->lang = $lang;
		 }

		include('../Application/translations/' . $lang . '.php');

		//Zend_Translate::setCache(Zend_Registry::get('cacheCore'));
		$adapter = new Zend_Translate('array', $translationArray, $lang);

		//load config for the current module
		$current_module = $frontController->getRequest()->getModuleName();
		$module_translation = _APP_ABSOLUTE_PATH . '/Application/modules/' . $current_module . '/translations/' . $lang . '.php';
		if(file_exists($module_translation) && is_readable($module_translation)) {
			include($module_translation);
		 	$translation_array = 'translation' . ucfirst($current_module);
		 	$adapter->addTranslation($$translation_array, $lang);
		 }
		Zend_Form::setDefaultTranslator($adapter);
		Zend_Registry::set('Zend_Translate', $adapter);
		Zend_Registry::set('LANGUAGES', $languages);
		Zend_Registry::set('lang', $lang);
		Zend_Registry::set('lang_id', $languages_id[strtolower($lang)]);
		Zend_Registry::set('langKey', $languages_id[strtolower($lang)]);
		
		/*foreach ($languages as $k=>$e) {
			Zend_Registry::set('lang_id', $k);
		}
		*/
	}
	
	/*
	 * Adaugare Pathuri catre helpere, atat action cat si view
	 */
	private function _registerHelpersPaths() {
		$layout = Zend_Layout::getMvcInstance();
 		if (false === $layout->getView()->getPluginLoader('helper')->getPaths('Netbridge_View_Helper')) {
				$layout->getView()->addHelperPath('Netbridge/View/Helper', 'Netbridge_View_Helper');
		} 
		Zend_Controller_Action_HelperBroker::addPrefix('Netbridge_Controller_Action_Helper_');
	}

	private function _initL10n(){
		$locale = new Zend_Locale('ro_RO');
	}
	/**
	 * runs before any controller is called.
	 */
	public function dispatchLoopStartup() {
		$front = Zend_Controller_Front::getInstance();
		$layout = Zend_Layout::getMvcInstance();

		//layout switcher
		switch($front->getRequest()->getControllerName()) {
			case 'frontend': $layout->setLayout('frontend'); break;
			case 'admin': $layout->setLayout('admin'); break;
			default : $layout->setLayout('frontend'); break;
		}

		//setting default reference value, if not set
		if (!Zend_Registry::isRegistered("module_references")) {
			Zend_Registry::set("module_references", array());
		}

		$modules = $front->getControllerDirectory();

		//load config for the current module
		$current_module = $front->getRequest()->getModuleName();
		$module_config = '../Application/modules/' . $current_module . '/config/config.php';
		if (file_exists($module_config) && is_readable($module_config)) {
			include($module_config);
		}

		//adding modules to the path
		foreach ($modules as $k => $v) {
			set_include_path(str_replace(DIRECTORY_SEPARATOR . 'controllers', '', $v) . PATH_SEPARATOR . get_include_path());
		}

		//disable layout if it's an AJAX call
		//TODO: remove this
//		if ($front->getRequest()->getParam('isAjaxCall') == 1) {
//			$layout->disableLayout();
//		}

		//start I18n
		$this->_initI18n();
		$this->_initL10n();
	}

	public function postDispatch() {

	}


	/**
	 * runs after all controller actions have finished.
	 */
	/*public function dispatchLoopShutdown() {
		$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
		$front = Zend_Controller_Front::getInstance();

		if (defined('_DEBUG_CONSOLE') && (_DEBUG_CONSOLE === TRUE) && !$viewRenderer->getNeverRender() && defined('_DB_PROFILER') && _DB_PROFILER ) {
			$db = Zend_Registry::get('dbAdapter');

			$profiler = $db->getProfiler();
			
			//Zend_Debug::dump($profiler->getQueryProfiles());

			$totalTime    = $profiler->getTotalElapsedSecs();
			$queryCount   = $profiler->getTotalNumQueries();
			$longestTime  = 0;
			$longestQuery = null;
			
			
			if ($queries = $profiler->getQueryProfiles()) {
				$debug_info = array();
				
				foreach ($queries as $query) {
				    if ($query->getElapsedSecs() > $longestTime) {
				        $longestTime  = $query->getElapsedSecs();
				        $longestQuery = $query->getQuery();
				    }
				    
				    $debug_info[] = '['.sprintf('%0.7f', $query->getElapsedSecs()).'] <em>' . $query->getQuery() . '</em>';
				}
				
				
				$debug_info[] = '<br><b>Query summary</b>: <br>Executed ' . $queryCount . ' queries in ' . sprintf('%0.7f', $totalTime) . ' seconds';
				$debug_info[] = 'Average query length: ' . sprintf('%0.7f', $totalTime / $queryCount) . ' seconds';
				$debug_info[] = 'Queries per second: ' . sprintf('%0.7f', $queryCount / $totalTime);
				$debug_info[] = 'Longest query length: ' . sprintf('%0.7f', $longestTime);
				$debug_info[] = "Longest query: <em>" . $longestQuery . '</em>';
				
				if (Zend_Registry::isRegistered('dbImportAdapter')) {
					$iprofiler = Zend_Registry::get('dbImportAdapter')->getProfiler();
					if ($queries = $iprofiler->getQueryProfiles()) {
						$debug_info[] = '<br /><b>Old site DB queries:</b>';
						foreach ($queries as $query) {
							$debug_info[] = '['.sprintf('%0.7f', $query->getElapsedSecs()).'] <em>' . $query->getQuery() . '</em>';
						}
					}
				}
				
				if ($startTime = $front->getParam('timeStart')) {
					$totalTime = microtime(true) - $startTime;
					$debug_info[] = "<br>Total execution time: <em>".$totalTime . "</em>";
				}
				
				$body = $front->getResponse()->getBody();
				
				$front->getResponse()->setBody(str_replace('</body>', '<div id="debug_toggler"><a href="#" onClick="$(\'#debug_console\').toggle(\'\');">Toggle console</a></div><div id="debug_console" style="display: none"><b>Query list</b>: <br>' . implode('<br>', $debug_info) . '</div></body>', $body));
				
//				$front->getResponse()->appendBody('<div id="debug_toggler"><a href="#" onClick="$(\'#debug_console\').toggle(\'\');">Toggle console</a></div><div id="debug_console" style="display: none"><strong>Query list</strong>: <br>' . implode('<br>', $debug_info) . '</div>');
			}
        }/
	}*/
}


